// Feeder.cs
//

using System.Collections.Generic;
using System.Diagnostics;
using System.Runtime.CompilerServices;
using System.Serialization;
using Awaiter;
using Nsb;
using Nsb.Classes;
using ThemeChain;
using WhirliGig.Classes;
using Yoshi.Classes;
using jQueryApi;

namespace PlayNexus.Classes
{
    public class Feeder : SavableData
    {
        private readonly bool curating = (bool) Storage.GetLocal(ThemeYoshi.CuratingKey);
        private Dictionary<string, object> _data;
        private List<FeedItem> _items;
        private string _key;
        private jQueryObject _line;
        private jQueryObject _list;
        private jQueryObject _listC;

        [PreserveName, PreserveCase]
        public static void Create(Gig gg, GigData gd)
        {
            Feeder cc = new Feeder();
            cc._key = cc.GetType().Name;
            gg.Element.Data(cc._key, cc);
            cc.Init(gd);
        }

        private void Init(GigData gd)
        {
            _data = gd.data ?? new Dictionary<string, object>();
            _line = GigShow.FindInGroup(gd.groupId, ".Line");
            _list = GigShow.FindInGroup(gd.groupId, ".List");
            _listC = _list.Find(Gig.DotGigContentClassName);
            Inform.Debug("line {0}, list {1}", _line.Length, _list.Length);
            if (curating)
            {
            }
            else
            {
                _line.Hide();
                FillList();
            }

            _list.Click(GenFeedEntry);
            //Script.Literal("debugger");
        }

        public void GenFeedEntry(jQueryEvent e)
        {
            string msg = Formulas.NewId;
            WriteToFeedAw(Await.AsyncAw, "home", msg);
        }

        public void FillList()
        {
            new Await()
                .AddAw(LoadAw)
                .AddAw(ShowAw)
                .Commit();
        }

        private void LoadAw(Await awp)
        {
            new Await()
                .AddAw(RetrieveBlobStringAw, (string) _data["partitionKey"], (string) _data["rowKey"])
                .HandleDl(Exceptions.BlobLoadError, Await.RethrowAw)
                .AddDx(delegate(Await aw)
                       {
                           //Inform.Debug("Loaded feed");
                           string content = CleanListData((string) aw[ResultRx]);
                           _items = (List<FeedItem>) (aw[ResultRx] != null ? Json.Parse("[" + content + "]") : null);
                       })
                .Commit(awp);
        }

        public void WriteToFeedAw(Await awp, string category, string msg)
        {
            Debug.Assert(category != null, "toId != null");
            FeedItem fd = new FeedItem(category, msg);

            new Await()
                .AddDl(delegate(Await aw) { AppendBlobStringAw(aw, (string) _data["partitionKey"], (string) _data["rowKey"], ResultRx, Json.Stringify(fd)); })
                .Commit(awp);
        }


        private void ShowAw(Await awp)
        {
            foreach (FeedItem item in _items)
            {
                AddLine(item);
            }
            awp.Done();
        }

        private void AddLine(FeedItem item)
        {
            jQueryObject line = _line.Clone(true, true);
            line
                .AppendTo(_listC)
                .Show()
                ;
            line.Find(Gig.DotGigContentClassName).Html(item.message);
        }
    }
}